package demo;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSplitPane;
import javax.swing.KeyStroke;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import demo.controler.AddressBookControler;
import demo.model.AddressBook;
import demo.view.ContactEdit;
import demo.view.ContactList;
import demo.view.ContactView;

public class Main {
	static boolean autoLoad = true;
	static boolean autoSave = false;

	public static final File DEFAULT_FILE = new File(System.getProperty(System
			.getProperty("user.home")), ".contacts");

	static Option[] options = new Option[] { new Option.Verbose(),
			new Option.Text("This are specific options"),
			new Option("--auto-save", "Save when application closes") {

				@Override
				protected void processOption(String name, String[] opts) {
					autoSave = true;
				}
			},

			new Option("--no-auto-load", "Don't try to open contacts") {

				@Override
				protected void processOption(String name, String[] opts) {
					autoLoad = false;
				}
			} };

	public static void main(String[] args) throws Exception {
		String[] rest = Option.processCommandLine(args, options);

		AddressBookControler ctrl = new AddressBookControler(new AddressBook());

		System.out.println(DEFAULT_FILE);
		if (autoLoad)
			loadFile(ctrl, DEFAULT_FILE, false);

		for (String file : rest) {
			loadFile(ctrl, new File(file), true);
		}

		JFrame main = new MainFrame(ctrl);
		main.setVisible(true);
	}

	public static void loadFile(AddressBookControler ctrl, File file,
			boolean fileMustExists) {
		try {
			ctrl.loadFromFile(file);
		} catch (IOException e) {
			if (!(e instanceof FileNotFoundException && !fileMustExists))
				JOptionPane.showMessageDialog(null, "Unable to open file '"
						+ file + "': " + e.getLocalizedMessage(),
						"Error loading file", JOptionPane.ERROR_MESSAGE);
		}
	}

	public static void saveFile(AddressBookControler ctrl, File file) {
		try {
			ctrl.saveToFile(file);
		} catch (ClassNotFoundException | IOException e) {
			JOptionPane.showMessageDialog(null, "Unable to save file '" + file
					+ "'" + e.getLocalizedMessage(), "Error loading file",
					JOptionPane.ERROR_MESSAGE);
		}
	}

	static class MainFrame extends JFrame {

		private static final long serialVersionUID = 1L;

		MainFrame(final AddressBookControler ctrl) {
			final ContactList lst = new ContactList(ctrl);
			final ContactView view = new ContactView(ctrl);

			lst.addListSelectionListener(new ListSelectionListener() {
				@Override
				public void valueChanged(ListSelectionEvent e) {
					view.bindToContact(lst.getSelectedValue());
				}
			});

			setTitle("My small address book");
			addWindowListener(new WindowAdapter() {
				public void windowClosing(WindowEvent e) {
					if (autoSave
							|| JOptionPane.showConfirmDialog(MainFrame.this,
									"Do you want to save before closing ?",
									"Save", JOptionPane.YES_NO_OPTION) == JOptionPane.OK_OPTION)
						saveFile(ctrl, DEFAULT_FILE);
				}
			});
			setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			add(new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(
					lst, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
					JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED), view));
			
			setJMenuBar(createMenu(ctrl));
			pack();
		}
		
		JMenuBar createMenu(final AddressBookControler ctrl){
			JMenuBar menu = new JMenuBar();
			JMenu fileMenu = new JMenu("File");
			fileMenu.setMnemonic(KeyEvent.VK_F);
			menu.add(fileMenu);
			
			JMenuItem create, importFile, exportFile, quit;
			fileMenu.add(create = new JMenuItem("Create contact", 'c'));
			create.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, KeyEvent.CTRL_MASK));

			fileMenu.add(importFile = new JMenuItem("Import ...", 'i'));
			importFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, KeyEvent.CTRL_MASK));
			fileMenu.add(exportFile = new JMenuItem("Export ...", 'e'));
			exportFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, KeyEvent.CTRL_MASK));
			fileMenu.add(new JSeparator());
			fileMenu.add(quit = new JMenuItem("Quit", 'q'));
			
			create.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
						ContactEdit editor = ContactEdit
								.getCreateWindows(ctrl);
						editor.setVisible(true);
					}
				}
			);

			importFile.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					JFileChooser fc = new JFileChooser();
					if(fc.showOpenDialog(MainFrame.this) == JFileChooser.APPROVE_OPTION)
						loadFile(ctrl, fc.getSelectedFile(), true);
				}
			});
			
			exportFile.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					JFileChooser fc = new JFileChooser();
					if(fc.showSaveDialog(MainFrame.this) == JFileChooser.APPROVE_OPTION)
						saveFile(ctrl, fc.getSelectedFile());
				}
			});

			quit.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					MainFrame.this.dispose();
					System.exit(0);
				}
			});
			return menu;
		}
	}
}
